package com.ldf.jrtsp.auth;

import com.ldf.jrtsp.parser.RtspUrlParser;
import com.ldf.jrtsp.utils.MD5Util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * rtsp digest鉴权
 *
 * @author lidaofu
 * @since 2024/6/19
 **/
public class RtspDigestAuth implements IRtspAuth {
    private static final Pattern noncePattern = Pattern.compile("nonce=\"([^\"]+)\"");
    private static final Pattern realmPattern = Pattern.compile("realm=\"([^\"]+)\"");
    private static final String DIGEST_AUTH_INFO = "Authorization: Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"\r\n";

    @Override
    public String calcAuthInfo(RtspUrlParser rtspUrlParser, String authInfoOriginal,String method) {
        Matcher nonceMatcher = noncePattern.matcher(authInfoOriginal);
        nonceMatcher.find();
        Matcher realmMatcher= realmPattern.matcher(authInfoOriginal);
        realmMatcher.find();
        String nonce = nonceMatcher.group(1);
        String realm = realmMatcher.group(1);
        String encrypt_1 = MD5Util.encrypt(rtspUrlParser.getUsername() + ":" + realm + ":" + rtspUrlParser.getPassword());
        String encrypt_2 = MD5Util.encrypt(method+":"+rtspUrlParser.getContentBase());
        String response = MD5Util.encrypt(encrypt_1 + ":" + nonce + ":" + encrypt_2);
        return String.format(DIGEST_AUTH_INFO, rtspUrlParser.getUsername(), realm, nonce, rtspUrlParser.getContentBase(), response);
    }


}
